<?php
    include 'Classes/User.class.php';
    
    class FollowDAO{
        private $connection;

        // Syndesh kai epilogh bashs
        function __construct(){
            $this->connection = mysql_connect('127.0.0.1', 'root', '')
                    or die('Could not connect: ' . mysql_error());
            mysql_select_db('travelbook', $this->connection)
                    or die('Could not select database');
        }

        // Kleisimo syndeshs me thn bash
        function __destruct(){
            if(isset($connection))
                mysql_close($connection);
        }

        // Epistrefei pinaka me tous followers enos xrhsth me krithrio to id
        function retrieveFollowers($userid){
            $query = "SELECT followerid FROM follow WHERE followingid='$userid'";
            $result = mysql_query($query);
            $followers = array();
            $i = 0;
            while($row = mysql_fetch_array($result)){
                $followers[$i] = $row['followerid'];
                $i++;
            }
            return $followers;
        }

        function insertFollow($follower,$following){

            $query = "INSERT INTO follow VALUES('$follower','$following')";
            mysql_query($query);
        }

        function removeFollow($follower,$following){

            $query = "DELETE FROM follow WHERE followerid = '$follower' AND followingid='$following'";
            mysql_query($query);
        }

        function checkFollow($follower,$following){

            $query = "SELECT * FROM follow WHERE followerid = '$follower' AND followingid='$following'";
            $result = mysql_query($query);
            if(mysql_num_rows($result) == 0){
                return false;
            }
            else{
                return true;
            }
        }

        // Epistrefei pinaka me tous following enos xrhsth me krithrio to id
        function retrieveFollowings($userid){
            $query = "SELECT * FROM user WHERE userid= ANY (SELECT followingid FROM follow WHERE followerid=$userid)";
            $result = mysql_query($query);
            $followers = array();
            while($row = mysql_fetch_array($result)){
                $followers[] = new User($row['userid'],
                                        $row['username'],
                                        $row['passwordhash'],
                                        $row['email'],
                                        $row['joindate'],
                                        $row['currentLocation']);
            }
            return $followers;
        }
    }
?>
